<template>
  <div>
  </div>
</template>

<script>
import { loginIm } from '@/api/rong-cloud'
export default {
  name: 'rong-cloud-im',
  props: {
    loginAccount: ''
  },
  data () {
    return {
      errMsg: {
        show: false,
        msg: ''
      },
      mediaStreamTrack: Object,
      loading: false,
      is_photo: false,
      layim: Object
    }
  },
  async created () {
    console.log(this.$store.state.user.severUserInfo.loginName, '直接在状态里面取值')
    let loginAccount = this.$store.state.user.severUserInfo.loginName
    if (loginAccount === '' || loginAccount === null || loginAccount === undefined) {
      console.log('对不起，请重新登录下，谢谢')
    }
    const that = this
    layui.use('layim', function (layim) {
      // 基础配置
      layim.config({

        // 初始化接口
        init: {
          url: 'Api/Api/getLayimInit',
          data: { account: loginAccount }
        },

        // 或采用以下方式初始化接口
        /*
           ,init: {
           mine: {
           "username": "LayIM体验者" //我的昵称
           ,"id": "100000123" //我的ID
           ,"status": "online" //在线状态 online：在线、hide：隐身
           ,"remark": "在深邃的编码世界，做一枚轻盈的纸飞机" //我的签名
           ,"avatar": "a.jpg" //我的头像
           }
           ,friend: []
           ,group: []
           }
           */

        // 查看群员接口
        members: {
          url: 'mock/layim_getmembers',
          data: {}
        },

        // 上传图片接口
        uploadImage: {
          url: '/Api/Api/rongCloudUpImg', // （返回的数据格式见下文）
          type: '' // 默认post
        },

        // 上传文件接口
        uploadFile: {
          url: '/upload/file', // （返回的数据格式见下文）
          type: '' // 默认post
        },

        isAudio: true, // 开启聊天工具栏音频
        isVideo: true, // 开启聊天工具栏视频

        // 扩展工具栏
        tool: [{
          alias: 'code',
          title: '代码',
          icon: '&#xe64e;'
        }],

        // brief: true, // 是否简约模式（若开启则不显示主面板）

        //, title: 'WebIM' //自定义主面板最小化时的标题
        //, right: '100px' //主面板相对浏览器右侧距离
        //, minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
        initSkin: '5.jpg', // 1-5 设置初始背景
        //, skin: ['aaa.jpg'] //新增皮肤
        //, isfriend: false //是否开启好友
        isgroup: false, // 是否开启群组
        min: true, // 是否始终最小化主面板，默认false
        notice: true, // 是否开启桌面消息提醒，默认false
        //, voice: false //声音提醒，默认开启，声音文件为：default.mp3

        msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html', // 消息盒子页面地址，若不开启，剔除该项即可
        find: layui.cache.dir + 'css/modules/layim/html/find.html', // 发现页面地址，若不开启，剔除该项即可
        chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html' // 聊天记录页面地址，若不开启，剔除该项即可

      })

      that.layim = layim

      // 监听在线状态的切换事件
      layim.on('online', function (data) {
        // console.log(data);
      })

      // 监听签名修改
      layim.on('sign', function (value) {
        // console.log(value);
      })

      // 监听自定义工具栏点击，以添加代码为例
      layim.on('tool(code)', function (insert) {
        layer.prompt({
          title: '插入代码',
          formType: 2,
          shade: 0
        }, function (text, index) {
          layer.close(index)
          insert('[pre class=layui-code]' + text + '[/pre]') // 将内容插入到编辑器
        })
      })

      // 监听layim建立就绪
      layim.on('ready', function (res) {
        // console.log(res.mine);

        // 模拟消息盒子有新消息，实际使用时，一般是动态获得

        // 添加好友（如果检测到该socket）
        layim.addList({
          type: 'group',
          avatar: 'http://tva3.sinaimg.cn/crop.64.106.361.361.50/7181dbb3jw8evfbtem8edj20ci0dpq3a.jpg',
          groupname: 'Angular开发',
          id: '12333333',
          members: 0
        })
        layim.addList({
          type: 'friend',
          avatar: 'http://tp2.sinaimg.cn/2386568184/180/40050524279/0',
          username: '冲田杏梨',
          groupid: 2,
          id: '1233333312121212',
          remark: '本人冲田杏梨将结束AV女优的工作'
        })
      })

      // 监听发送消息
      layim.on('sendMessage', function (data) {
        let To = data.to
        let Mine = data.mine
        console.log(data, '监听发送的消息-调用sdk发送消息')
        that.sendTextMsg(To.id, Mine.content)
        if (To.type === 'friend') {
          layim.setChatStatus('<span style="color:#FF5722;">发送中...</span>')
        }
      })

      // 监听查看群员
      layim.on('members', function (data) {
        // console.log(data);
      })

      // 监听聊天窗口的切换
      layim.on('chatChange', function (res) {
        var type = res.data.type
        console.log(res.data.id)
        if (type === 'friend') {
          // 模拟标注好友状态
          // layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
        } else if (type === 'group') {
          // 模拟系统消息
          layim.getMessage({
            system: true,
            id: res.data.id,
            type: 'group',
            content: '模拟群员' + (Math.random() * 100 | 0) + '加入群聊'
          })
        }
      })
    })
    RongIMLib.RongIMClient.init('vnroth0kvboio')
    RongIMClient.setConnectionStatusListener({
      onChanged: function (status) {
        // status 标识当前连接状态
        switch (status) {
          case RongIMLib.ConnectionStatus.CONNECTED:
            console.log('链接成功')
            break
          case RongIMLib.ConnectionStatus.CONNECTING:
            console.log('正在链接')
            break
          case RongIMLib.ConnectionStatus.DISCONNECTED:
            console.log('断开连接')
            break
          case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
            console.log('其他设备登录')
            break
          case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            console.log('域名不正确')
            break
          case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
            console.log('网络不可用')
            break
        }
      }
    })
    // 消息监听器
    RongIMClient.setOnReceiveMessageListener({
      // 接收到的消息
      onReceived: function (message) {
        // 判断消息类型
        console.log(message, '监听到的消息')
        switch (message.messageType) {
          case RongIMClient.MessageType.TextMessage:
            // message.content.content => 文字内容
            that.showRongColudMsg(message.senderUserId, message.content.content)
            break
          case RongIMClient.MessageType.VoiceMessage:
            // message.content.content => 格式为 AMR 的音频 base64
            break
          case RongIMClient.MessageType.ImageMessage:
            // message.content.content => 图片缩略图 base64
            // message.content.imageUri => 原图 URL
            break
          case RongIMClient.MessageType.LocationMessage:
            // message.content.latiude => 纬度
            // message.content.longitude => 经度
            // message.content.content => 位置图片 base64
            break
          case RongIMClient.MessageType.RichContentMessage:
            // message.content.content => 文本消息内容
            // message.content.imageUri => 图片 base64
            // message.content.url => 原图 URL
            break
          case RongIMClient.MessageType.InformationNotificationMessage:
            // do something
            break
          case RongIMClient.MessageType.ContactNotificationMessage:
            // do something
            break
          case RongIMClient.MessageType.ProfileNotificationMessage:
            // do something
            break
          case RongIMClient.MessageType.CommandNotificationMessage:
            // do something
            break
          case RongIMClient.MessageType.CommandMessage:
            // do something
            break
          case RongIMClient.MessageType.UnknownMessage:
            if (message.objectName === 'LY:AddFriend') {
              console.log('收到添加好友消息')
              that.layim.msgbox(1)
            }
            break
          default:
          // do something
        }
      }
    })
    console.log(that.loginAccount, '打印登录的账号是什么')
    let imInfo = await loginIm(loginAccount)
    console.log(imInfo, '获取im登录信息1')
    var token = imInfo.data.result.token
    RongIMClient.connect(token, {
      onSuccess: function (userId) {
        console.log('Connect successfully. ' + userId)
      },
      onTokenIncorrect: function () {
        console.log('token 无效')
      },
      onError: function (errorCode) {
        var info = ''
        switch (errorCode) {
          case RongIMLib.ErrorCode.TIMEOUT:
            info = '超时'
            break
          case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
            info = '不可接受的协议版本'
            break
          case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
            info = 'appkey不正确'
            break
          case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
            info = '服务器不可用'
            break
        }
        console.log(info)
      }
    })
    let callback = {
      onSuccess: function (userId) {
        console.log('Reconnect successfully. ' + userId)
      },
      onTokenIncorrect: function () {
        console.log('token无效')
      },
      onError: function (errorCode) {
        console.log(errorcode)
      }
    }
    let config = {
      // 默认 false, true 启用自动重连，启用则为必选参数
      auto: true,
      // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
      url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
      // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
      rate: [100, 1000, 3000, 6000, 10000]
    }
    RongIMClient.reconnect(callback, config)
  },
  watch: {
  },
  methods: {
    sendTextMsg (to, text) {
      let that = this
      var msg = new RongIMLib.TextMessage({ content: String(text), extra: '附加信息' })
      var conversationType = RongIMLib.ConversationType.PRIVATE // 单聊, 其他会话选择相应的消息类型即可
      var targetId = String(to) // 目标 Id
      RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, {
        onSuccess: function (message) {
          // message 为发送的消息对象并且包含服务器返回的消息唯一 Id 和发送消息时间戳
          console.log('Send successfully')
          that.layim.setChatStatus('<span style="color:#FF5722;">消息已送达</span>')
        },
        onError: function (errorCode, message) {
          var info = ''
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = '超时'
              break
            case RongIMLib.ErrorCode.UNKNOWN:
              info = '未知错误'
              break
            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
              info = '在黑名单中，无法向对方发送消息'
              break
            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
              info = '不在讨论组中'
              break
            case RongIMLib.ErrorCode.NOT_IN_GROUP:
              info = '不在群组中'
              break
            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
              info = '不在聊天室中'
              break
          }
          console.log('发送失败: ' + info + errorCode)
        }
      })
    },
    // 展示收到好友的消息
    showRongColudMsg (id, content) {
      let To1 = { type: 'friend', name: 'L0001', avatar: 'http://tp1.sinaimg.cn/1571889140/180/40030060651/1', id: id, content: content }
      let that = this
      let obj = {}
      if (To1.type === 'group') {
        obj = {
          username: '模拟群员' + (Math.random() * 100 | 0),
          avatar: layui.cache.dir + 'images/face/' + (Math.random() * 72 | 0) + '.gif',
          id: To1.id,
          type: To1.type,
          content: To1.content
        }
      } else {
        obj = {
          username: To1.name,
          avatar: To1.avatar,
          id: To1.id,
          type: To1.type,
          content: To1.content
        }
        that.layim.setChatStatus('<span style="color:#FF5722;">在线</span>')
      }
      that.layim.getMessage(obj)
    }
  }
}
</script>
